package com.zenika.zenbinding.client.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class ListBoxHandler extends ListBindingHandler implements ChangeListener {

	private ListBox listBox;
	private HashMap objectToIndex;

	public ListBoxHandler(ListBox listBox, List valueList) {
		super();
		this.listBox = listBox;
		this.listBox.addChangeListener(this);
		this.objectToIndex = new HashMap();
		this.setChoices(valueList);
	}

	public void onChange(Widget sender) {
		ArrayList selectedItems = new ArrayList();
		int itemCount = this.listBox.getItemCount();
		for (int i = 0; i < itemCount; i++) {
			if (this.listBox.isItemSelected(i)) {
				String label = this.listBox.getItemText(i);
				selectedItems.add(this.getObject(label));
			}
		}
		this.fireChange(selectedItems);
	}

	public void setErrorStyle() {
		this.listBox.setStyleName("error-ListBox");
	}

	public void setRegularStyle() {
		this.listBox.setStyleName("gwt-ListBox");
	}

	public void addItem(String item) {
		this.listBox.addItem(item);
		Integer index = new Integer(this.listBox.getItemCount() - 1);
		this.objectToIndex.put(this.getObject(item), index);
	}

	public int getIndex(String item) {
		int itemCount = this.listBox.getItemCount();
		for (int i = 0; i < itemCount; i++) {
			if (this.listBox.getItemText(i).equals(item)) {
				return i;
			}
		}
		return -1;
	}

	public void setItemSelected(String item, boolean selected) {
		int index = this.getIndex(item);
		this.listBox.setItemSelected(index, true);
	}

	public Widget getWidget() {
		return this.listBox;
	}

	public Object getValue() {
		// FIXME multiple choices?
		return this.listBox.getValue(this.listBox.getSelectedIndex());
	}

}
